
from datetime import datetime
from util import *

def getETFHolding(code,dateTime):
    # 目标 URL
    base_url = "https://reportdocs.static.szse.cn/files/text/etf/ETF{}{}.txt"
    url = base_url.format(code,dateTime)

    return get_with_headers_requests(url,{},False)

def extract_portfolio_info(data):
    """
    从ETF申购赎回清单文件中提取组合信息
    
    参数:
        resp: 响应数据
    返回:
        portfolio_data: 包含证券代码、证券简称和股份数量的列表
    """
    portfolio_data = []
    in_portfolio_section = False
    
    try:

        # 定位组合信息部分并提取数据
        for line in data:
            
            # 找到组合信息的起始行
            if "组合信息内容" in line:
                in_portfolio_section = True
                continue
            
            # 跳过非组合信息部分
            if not in_portfolio_section:
                continue
            
            # 跳过分隔行和标题行
            if "-------------------------------------------------------------------------------------------------------------------------------------------------------" in line:
                continue
            if "证券代码" in line and "证券简称" in line and "股份数量" in line:
                continue
            
            # 提取有效数据行
            line = line.strip()
            if not line:
                continue
            
            # 解析数据（假设数据列用空格分隔）
            parts = line.split()
            if len(parts) >= 3:
                # 处理可能的逗号分隔的数字（如1,200）
                sec_code = parts[0]
                sec_name = parts[1]
                # 合并可能被分割的股份数量（处理逗号）
                share_count = ''.join(parts[2:3]).replace(',', '')
                
                portfolio_data.append({
                    'INSTRUMENT_ID': sec_code,
                    'INSTRUMENT_NAME': sec_name,
                    'QUANTITY': share_count
                })
    
    except Exception as e:
        print(f"读取数据时发生错误: {e}")
    
    return portfolio_data

# 保存深交所的持仓情况
def saveShenHoding(code):
  yesterday = get_previous_workday_with_holidays(datetime.now().date())
  # dateformat ： yyyyMMdd
  resp = getETFHolding(code, yesterday)
  array = resp.split("\n")
  hodingResult = extract_portfolio_info(array)
  save_to_csv(hodingResult,code,yesterday)

# https://investor.szse.cn/disclosure/fund/currency/index.html
# 深交所可能要重做。这里有现成的接口可使用
if __name__ == "__main__":
  saveShenHoding("159581")